package cn.wolfcode.web.controller;

import cn.wolfcode.transfer.domain.Permission;
import cn.wolfcode.transfer.domain.Role;
import cn.wolfcode.transfer.qo.QueryObject;
import cn.wolfcode.transfer.service.IRoleService;
import cn.wolfcode.transfer.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
  
    @RequiredPermission(name = "角色页面" , expression = "role:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.getPageInfo(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "role/list";
    }

    @RequiredPermission(name = "角色删除",expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id!=null){
            roleService.deleteByPrimaryKey(id);
        }

        return "redirect:/role/list";
    }

    @RequiredPermission(name = "角色新增/编辑",expression = "role:saveOrUpdate")
    @RequestMapping("/input")
    public String update(Long id ,Model model){
        if (id!=null){
            Role role = roleService.selectByPrimaryKey(id);
            model.addAttribute("role",role);
            List<Permission> permissions = roleService.selectPermission(id);
            model.addAttribute("permissions",permissions);
        }
        List<Permission> permissionsAll = roleService.selectPermissionAll();
        model.addAttribute("permissionsAll",permissionsAll);
        return  "role/input";
    }

    @RequiredPermission(name = "角色新增/编辑",expression = "role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role , Long[] ids){
        if(role.getId() == null){ // 新增
                roleService.insert(role,ids);
        }else {
                roleService.updateByPrimaryKey(role, ids); // 修改
        }
        return "redirect:/role/list"; // 让浏览器重新发一次请求
    }

}
